package com.casa.POI.dianping;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public abstract class ThreadsExecutor extends Executor {

	private ExecutorService executorService;

	@Override
	public void execute() {
		super.execute();
		while (true) {
			List<? extends Runnable> works = getNextBatchWorks();
			if (works == null || works.size() == 0) {
				break;
			}
			
			Console.rewrite("processing %d work items...", works.size());
			
			this.resetExecutorService();
			for (Runnable work : works) {
				this.executorService.execute(work);
			}
			this.executorService.shutdown();
			try {
				this.executorService.awaitTermination(1, TimeUnit.HOURS);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void resetExecutorService() {
		this.executorService = Executors.newFixedThreadPool(getMaxThreads());
	}

	public int getMaxThreads() {
		return ConfigurationManager.getInstance().getMaxThreads();
	}

	protected abstract List<? extends Runnable> getNextBatchWorks();

}
